package util;

import org.sqlite.SQLiteConfig;
import org.sqlite.SQLiteDataSource;

import javax.sql.DataSource;
import java.io.File;
import java.sql.*;


public class DBUtil {
    //单例数据源
    private  volatile  static DataSource DATASOURCE;
    //单例数据库连接
    private volatile static Connection CONNECTION;

    private static DataSource getDataSource() {
        if(DATASOURCE == null) {
            synchronized (DBUtil.class) {
                if(DATASOURCE == null) {
                    SQLiteConfig config = new SQLiteConfig();
                    config.setDateStringFormat(Util.DATE_PATTERN);
                    DATASOURCE = new SQLiteDataSource(config);
                    //配置数据源得URL是SQLite独有的需要向下转型
                    ((SQLiteDataSource)DATASOURCE).setUrl(getUrl());
                }
            }
        }
        return DATASOURCE;
    }
    private static String getUrl() {
        String path = "D:\\search-everything\\target";
        String url = "jdbc:sqlite://" + path + File.separator + "search_everything.db";
        System.out.println("获取数据库的连接为 : " + url);
        return url;
    }
    public static Connection getConnection() throws SQLException {
        if (CONNECTION == null) {
            synchronized (DBUtil.class) {
                if (CONNECTION == null) {
                    CONNECTION = getDataSource().getConnection();
                }
            }
        }
        return CONNECTION;
    }

    public static void main(String[] args) throws SQLException {
        System.out.println(getConnection());
    }

    public static void close(Statement statement) {
        if(statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(PreparedStatement preparedStatement, ResultSet resultSet) {
        close(preparedStatement);
        if(resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
